package com.linxin.ai_automates_periodontal_treatment_system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.linxin.ai_automates_periodontal_treatment_system.common.Result;
import com.linxin.ai_automates_periodontal_treatment_system.entity.TreatmentPlan;
import com.linxin.ai_automates_periodontal_treatment_system.service.TreatmentPlanService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/treatmentPlan")
public class TreatmentPlanController {
    @Autowired
    private TreatmentPlanService treatmentPlanService;

    @GetMapping("getTreatmentPlan/{patientId}/{recordId}")
    public Result<TreatmentPlan> getTreatmentPlan(@PathVariable("patientId") Integer patientId,
                                                  @PathVariable("recordId") Integer recordId) {

        // 根据病人id和医生id获取治疗方案
        LambdaQueryWrapper<TreatmentPlan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TreatmentPlan::getPatientId, patientId).eq(TreatmentPlan::getDiagnosticRecordId, recordId);
        // 获取一个
        TreatmentPlan treatmentPlan = treatmentPlanService.getOne(queryWrapper);
        if (treatmentPlan == null) {
            return Result.success(null);
        } else {
            return Result.success(treatmentPlan);
        }
    }

    /**
     * 保存或更新治疗方案
     */
    @PostMapping("saveTreatmentPlan/{patientId}/{recordId}")
    public Result<String> saveTreatmentPlan(@PathVariable("patientId") Integer patientId,
                                                   @PathVariable("recordId") Integer recordId,
                                                   @RequestBody TreatmentPlan treatmentPlan,
                                                   HttpServletRequest request) {

        Integer doctorId = (Integer) request.getAttribute("doctorId");
        treatmentPlan.setPatientId(patientId);
        treatmentPlan.setDiagnosticRecordId(recordId);
        treatmentPlan.setDoctorId(doctorId);

        if (treatmentPlan.getId() == null){
            // 设置创建时间
            treatmentPlan.setCreateTime(LocalDateTime.now());
            // 设置更新时间
            treatmentPlan.setUpdateTime(LocalDateTime.now());
            // 新增
            treatmentPlanService.save(treatmentPlan);
        } else {
            // 设置更新时间
            treatmentPlan.setUpdateTime(LocalDateTime.now());
            // 更新
            treatmentPlanService.updateById(treatmentPlan);
        }

        return Result.success("保存或更新治疗方案成功");
    }
}
